package club.gggd.qqrobot.schedule;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * @Description 定时清除随机图片缓存的图片
 * @Author srx
 * @date 2022/9/6 16:29
 */
@Component
@EnableScheduling
@Slf4j
public class ClearFileSchedule {

    @Value("${path.random-picture.path}")
    private String basePath;

    /**
     * 每天凌晨4点触发
     */
    @Scheduled(cron = "0 0 4 * * ?")
    public void clearFile(){
        log.info("开始清除随机图片缓存...");
        long s = System.currentTimeMillis();

        File file = new File(basePath);
        if(file.exists()){
            File[] files = file.listFiles();
            int size = 0;
            for (File f : files) {
                boolean result = f.delete();
                if(result){
                    size++;
                }
            }

            log.info("已成功清除文件{}份，耗时：{}ms", size, System.currentTimeMillis() - s);
        }

    }
}
